import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Space, message, Select, Switch, Spin } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { history, useParams } from '@umijs/max';

import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import type { User, UserRequest } from '@/services/generated';

const { Option } = Select;

const UserEdit: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [userInfo, setUserInfo] = useState<User | null>(null);

  // 获取用户详情
  const fetchUserDetail = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.users.usersRetrieve({ id: parseInt(id!) });
      setUserInfo(response.data);
      
      // 设置表单初始值
      form.setFieldsValue({
        username: response.data.username,
        email: response.data.email,
        real_name: response.data.real_name,
        phone: response.data.phone,
        status: response.data.status,
        is_staff: response.data.is_staff,
        is_superuser: response.data.is_superuser,
        is_active: response.data.is_active,
        department_id: response.data.department_id,
      });
    } catch (error: any) {
      console.error('获取用户详情失败:', error);
      message.error('获取用户详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 更新用户信息
  const handleSubmit = async (values: UserRequest) => {
    if (!id) return;
    
    try {
      setSubmitting(true);
      await autoLoginInDev();
      await apiClients.users.usersUpdate({
        id: parseInt(id!),
        userRequest: values
      });
      message.success('用户信息更新成功');
      history.push(`/user/detail/${id}`);
    } catch (error: any) {
      console.error('更新用户信息失败:', error);
      // API中间件已经处理了错误显示
    } finally {
      setSubmitting(false);
    }
  };

  useEffect(() => {
    fetchUserDetail();
  }, [id]);

  return (
    <PageContainer
      title="编辑用户"
      extra={
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => history.back()}
        >
          返回
        </Button>
      }
    >
      <Spin spinning={loading}>
        <Card>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{
              status: 'active',
              is_staff: false,
              is_superuser: false,
              is_active: true,
            }}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[
                { required: true, message: '请输入用户名!' },
                { min: 3, message: '用户名至少3个字符!' },
              ]}
            >
              <Input placeholder="用户名" />
            </Form.Item>

            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: '请输入邮箱!' },
                { type: 'email', message: '请输入有效的邮箱地址!' },
              ]}
            >
              <Input placeholder="邮箱地址" />
            </Form.Item>

            <Form.Item
              name="real_name"
              label="真实姓名"
            >
              <Input placeholder="真实姓名" />
            </Form.Item>

            <Form.Item
              name="phone"
              label="手机号"
            >
              <Input placeholder="手机号" />
            </Form.Item>

            <Form.Item
              name="status"
              label="用户状态"
              rules={[{ required: true, message: '请选择用户状态!' }]}
            >
              <Select placeholder="请选择用户状态">
                <Option value="active">激活</Option>
                <Option value="inactive">未激活</Option>
                <Option value="suspended">暂停</Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="department_id"
              label="部门ID"
            >
              <Input placeholder="部门ID（可选）" type="number" />
            </Form.Item>

            <Form.Item
              name="is_active"
              label="账户激活"
              valuePropName="checked"
            >
              <Switch checkedChildren="激活" unCheckedChildren="禁用" />
            </Form.Item>

            <Form.Item
              name="is_staff"
              label="管理员权限"
              valuePropName="checked"
            >
              <Switch checkedChildren="是" unCheckedChildren="否" />
            </Form.Item>

            <Form.Item
              name="is_superuser"
              label="超级管理员"
              valuePropName="checked"
            >
              <Switch checkedChildren="是" unCheckedChildren="否" />
            </Form.Item>

            <Form.Item>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={submitting}
                  icon={<SaveOutlined />}
                >
                  保存
                </Button>
                <Button onClick={() => history.back()}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </Spin>
    </PageContainer>
  );
};

export default UserEdit;
